package com.app.shortvideo.ext

import android.view.View
import androidx.lifecycle.viewModelScope
import com.app.shortvideo.net.base.BaseResponseBean
import com.app.library.base.ApiException
import com.app.library.base.LibViewModel
import com.app.library.utils.ClickHelper
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * 统一处理点击事件
 * @param pos 点击位置
 */
fun View.clickListener(
    pos: String? = null,
    click: (v: View) -> Unit
) {
    setOnClickListener {
        if (ClickHelper.isFastDoubleClick()) {
            return@setOnClickListener
        }
        pos?.let {
        }
        click.invoke(it)
    }
}

/**
 * ViewModel扩展方法：启动协程
 *
 * @param block 协程逻辑
 * @param onFailure 错误回调方法
 * @param onSuccess 完成回调方法
 */
fun <T> LibViewModel.launchRequest(
    block: suspend CoroutineScope.() -> BaseResponseBean<T?>,
    onFailure: (e: Throwable) -> Unit = { _: Throwable -> },
    onSuccess: (result: T?) -> Unit = {}
): Job {
    return viewModelScope.launch(
        CoroutineExceptionHandler { _, throwable ->
            run {
                loadComplete()
                onFailure(throwable)
            }
        }
    ) {
        val rsp = block.invoke(this)
        if (rsp.isSuccess) {
            onSuccess.invoke(rsp.data)
        } else {
            onFailure(ApiException(rsp.code ?: "999", rsp.message))
        }
        loadComplete()
    }
}
